package com.kaaction.modules.crab.api;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.DocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kaaction.common.utils.CacheUtils;
import com.kaaction.common.web.BaseController;
import com.kaaction.modules.crab.service.CouponDetailService;
import com.kaaction.modules.crab.service.OrderService;


@Controller
@RequestMapping(value = "/api/v1/crabLoginApi")
public class CrabLoginApi extends BaseController{
	
	
	@Autowired
	CouponDetailService couponDetailService;
	
	@Autowired
	OrderService orderService;
	
	/**
	 * 验证登入
	 * 
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 * @throws DocumentException
	 */
	@RequestMapping(value = "/loginCheck")
	public void selRecommendProduct(HttpServletRequest request, HttpServletResponse response)
			throws UnsupportedEncodingException, DocumentException {
		
		String cardNum = (String) request.getParameter("cardNum");
		String password = (String)request.getParameter("password") ;
		String number = (String) request.getParameter("vcode").toLowerCase();
		
		Object code = CacheUtils.get("kaaCode"+request.getRemoteAddr());
		logger.info("code="+code);
		if(code!=null){
			
			
			if(number.equals(code.toString().toLowerCase())){
				
				Map<String,Object>  map = couponDetailService.selCoupon(cardNum,"");
				
				if(map!=null&&map.size()>0){
					
					if(password.equals(map.get("password").toString())){
						String  useState = (String) map.get("useState");
						if("0".equals(useState)){
							super.writeAjaxResponse(response,"0");
						}else{
							map = orderService.selCoupon(cardNum,password);
							String  state = (String) map.get("state");
							if("0".equals(state)){
								super.writeAjaxResponse(response,"1");
							}else{
								super.writeAjaxResponse(response,"2");
							}
						}
						
					}else{
						super.writeFailResponse(response, null, "密码不正确");
					}
				}else{
					super.writeFailResponse(response, null, "兑换券卡号不正确或未激活");
				}
			}else{
				super.writeFailResponse(response, null, "验证码不正确");
			}
		}else{
			super.writeFailResponse(response, null, "验证码失效");
		}
		
	}
}
